<template>
    <div class="layout_voice">
        <el-checkbox-group v-model="checkedList" class="group" @change="handleChange">
            <el-row :gutter="16">
                <el-col v-for="item in props.voiceData" :key="item.id" :span="6" class="outer">
                    <div class="container_img">
                        <div class="checked">
                            <el-checkbox :label="item.id"></el-checkbox>
                        </div>
                        <div v-show="item.is_radar" class="radar_icon"></div>
                        <div class="audio">
                            <audio :src="item.absolute_url" controls>您的浏览器不支持音频audio标签。</audio>
                        </div>
                    </div>
                    <div class="container_text">
                        <div class="tag_box">
                            <el-popover
                                v-if="item.tags?.length > 0 || item.share_tags?.length > 0"
                                :width="300"
                                trigger="hover"
                                popper-class="auto_width">
                                <template #reference>
                                    <div class="zw-el-tags">
                                        <el-tag v-for="tag in getTags(item.tags, item.share_tags, 1)" :key="tag.id">
                                            {{ tag.name }}
                                        </el-tag>
                                    </div>
                                </template>
                                <template #default>
                                    <div class="zw-el-tags">
                                        <el-tag v-for="tag in getTags(item.tags, item.share_tags, 2)" :key="tag.id">
                                            {{ tag.name }}
                                        </el-tag>
                                    </div>
                                </template>
                            </el-popover>
                        </div>
                        <div class="describe">
                            <span class="describe_text" :title="item.file_name"> {{ item.file_name }} </span>
                        </div>
                        <div class="time">
                            <span>{{ item.created_at }}</span>
                            <span>上传者：{{ item.user_name }}</span>
                        </div>
                    </div>
                    <div class="iconList">
                        <template v-for="(icon, key) in item.compilesss">
                            <div
                                v-if="item.is_radar"
                                :key="key"
                                v-auth="power[key]"
                                class="icon_item"
                                @click="select(item, key)">
                                <el-tooltip class="box-item" effect="dark" :content="icon.content" placement="top">
                                    <img
                                        :id="key.toString()"
                                        :src="`/static/material/compile${icon.isShow ? 'Red' : ''}Icon${key + 1}.png`"
                                        alt=""
                                        @mouseover="item.compilesss[key].isShow = true"
                                        @mouseout="item.compilesss[key].isShow = false" />
                                </el-tooltip>
                            </div>
                            <div
                                v-if="item.is_radar == 0 && key != 0"
                                :key="key"
                                v-auth="power[key]"
                                class="icon_item"
                                @click="select(item, key)">
                                <el-tooltip class="box-item" effect="dark" :content="icon.content" placement="top">
                                    <img
                                        :id="key.toString()"
                                        :src="`/static/material/compile${icon.isShow ? 'Red' : ''}Icon${key + 1}.png`"
                                        alt=""
                                        @mouseover="item.compilesss[key].isShow = true"
                                        @mouseout="item.compilesss[key].isShow = false" />
                                </el-tooltip>
                            </div>
                        </template>
                    </div>
                </el-col>
            </el-row>
        </el-checkbox-group>
        <!-- 删除弹框 -->
        <ZWDeletdialog ref="DeletdialogRef" @submit="batchRemove" />
    </div>

    <ShareConfiguration v-if="isShowConfiguration" :id="content_id" v-model:show="isShowConfiguration" :type="3" />
</template>

<script setup lang="ts">
import BenzAMRRecorder from 'benz-amr-recorder';
import ZWDeletdialog from '@/components/ZWDeletdialog.vue';
import { removeBaseMaterial, getImageList, batchContentDel, batchDownLoad } from '@/api/concreation';
import { ElMessage } from 'element-plus';
import { ref, reactive, onUnmounted } from 'vue';
import { useStore } from '@/store';
import bus from '@/utils/bus';
import { useRouter } from 'vue-router';
import useClipboard from 'vue-clipboard3';
import ShareConfiguration from '@/components/common/ShareConfiguration.vue';
import { endLoading, startLoading } from '@/utils/request';

const router = useRouter();
const store = useStore();
const props = defineProps(['voiceData']);
const emit = defineEmits(['submit']);
const checkedList = ref([]); // 选中图片的 id
const isBatch = ref(false); // 是否为批量删除
const DeletdialogRef = ref(null);
const delArr = ref([]); // 删除数组
const selectId = ref(0); // 图片内容编辑卡片 id
const selectItem = ref({}); // 选中编辑的每项数据
const selectKey = ref(); // 选中编辑栏的 key
const downImage = ref([]); // 下载图片id
const power = ref(['LOOK_DETAILS_AD', 'DEL_AD', 'DOW_AD', 'EDIT_AD']);
const isShowConfiguration = ref<boolean>(false);
const content_id = ref<number>(0);

const itemSpan = ref(6);
//播放时长
const currentTime = ref(0);
const amrTime = ref(0);
const isPlay = ref(false);
const { toClipboard } = useClipboard();
// 播放
// const ARMplay = (url:string,id:number)=>{
//   const oDom = document.querySelector('.audio_'+id);
//   const amr = new BenzAMRRecorder();
//   amr.initWithUrl(url).then(() => {
//     if(amr.pause){
//       amr.play()
//     }else{
//       amr.pause();
//     }
//     amrTime.value= amr.getDuration() //音频总时长
//       console.log(amrTime.value,3333333);
//   })
// }
// 是否是amr格式
const isAmr = (file: string) => {
    return file.substring(file.lastIndexOf('.')) == '.amr';
};
//合并
const getTags = (arr1: any, arr2: any, type: any) => {
    if (type == 1) {
        return arr1.concat(arr2).slice(0, 4);
    } else {
        return arr1.concat(arr2);
    }
};
// 编辑操作部分
const select = (item: any, key: any) => {
    selectItem.value = item;
    selectKey.value = item.compilesss[key].name;
    item.compilesss[key].isShow = true;
    if (selectKey.value === 'delete') {
        selectId.value = item.id;
        delArr.value.push(item.id);
        isBatch.value = false;
        DeletdialogRef.value.appDialog.visible = true;
    } else if (selectKey.value === 'write') {
        bus.emit('editItem', item);
        store.dispatch('content/upload', {
            uploadVisib: true,
            title: '编辑音频'
        });
    } else if (selectKey.value === 'statistics') {
        router.push(`/content/basematerial/statement?id=${item.id}&title=${item.title}`);
    } else if (selectKey.value === 'download') {
        batchDownLoad({
            material_ids: [item.id],
            material_type: 3
        }).then((res: any) => {
            window.open(res.url);
            // clearSelection();
        });
        // window.open(item.absolute_url)
    } else if (selectKey.value == 'copy') {
        if (item.is_radar) {
            content_id.value = item.id;
            isShowConfiguration.value = true;
        } else {
            onCopy(item.absolute_url);
        }
    }
};
// 删除确认弹框
const batchRemove = () => {
    startLoading();
    if (!isBatch.value) {
        const params = {
            type: 3,
            content_ids: delArr.value
        };
        batchContentDel(params)
            .then((res: any) => {
                ElMessage.success('删除成功');
                DeletdialogRef.value.appDialog.visible = false;
                emit('submit');
            })
            .catch(() => {
                endLoading();
            });
    } else {
        const params = {
            type: 3,
            content_ids: checkedList.value
        };
        batchContentDel(params)
            .then((data: any) => {
                ElMessage.success('批量删除成功');
                DeletdialogRef.value.appDialog.visible = false;
                emit('submit');
            })
            .catch((e: any) => {
                ElMessage.error(e.msg);
                endLoading();
            });
    }
};
// 批量删除
const isBatchDel = () => {
    isBatch.value = true;
    DeletdialogRef.value.appDialog.visible = true;
};
// 多选
const handleChange = (value: string[]) => {
    const checkedCount = value.length;
    const checkAll = checkedCount === props.voiceData.length;
    bus.emit('change', checkedList.value);
    bus.emit('autoCheckedAll', checkAll);
    bus.emit('voiceId', checkedList.value);
    store.dispatch('table', {
        tableData: value
    });
};
const clearSelection = () => {
    bus.emit('change', []);
    bus.emit('voiceId', []);
    bus.emit('autoCheckedAll', false);
    store.dispatch('table', {
        tableData: []
    });
    checkedList.value = [];
};

// 全选
const checkAll = (value: any) => {
    if (value) {
        props.voiceData.forEach(item => {
            checkedList.value.push(item.id);
            store.dispatch('table', {
                tableData: checkedList,
                tableAll: true
            });
        });
        bus.emit('voiceId', checkedList.value);
        bus.emit('imageId', checkedList.value);
    } else {
        checkedList.value = [];
    }
};

// 复制
const onCopy = async (v: any) => {
    try {
        await toClipboard(v);
        ElMessage.success('复制成功');
    } catch (e) {
        ElMessage.error('复制失败');
    }
};

// 主动暴露方法
defineExpose({ isBatchDel, clearSelection });
// 添加全选监听事件
bus.on('checkAll', checkAll);
onUnmounted(() => {
    store.dispatch('table', {
        tableData: [],
        tableAll: true
    });
    bus.off('checkAll', checkAll);
});
// 修改 popover 样式
const style = reactive({
    display: 'flex',
    color: '#ff6b00',
    'flex-wrap': 'wrap'
});
const tagStyle = reactive({
    border: '.0625rem solid #ffc69e',
    padding: '0 .25rem',
    'white-space': 'nowrap',
    'line-height': '1.375rem',
    margin: '0 .3125rem .625rem'
});
</script>

<style lang="scss" scoped>
.layout_voice {
    width: 100%;
}

.outer {
    padding: 0.5rem;

    .container_img {
        position: relative;

        .checked {
            position: absolute;
            left: 0.8125rem;

            :deep .el-checkbox__label {
                display: none;
            }
        }

        .play_icon {
            width: 0.8125rem;
            height: 0.9375rem;
            background: url('@/assets/image/material/play_icon.png') no-repeat;
            background-size: 100%;
            position: absolute;
            top: 1rem;
            left: 2.9375rem;
            z-index: 99;
        }

        .suspend_icon {
            width: 0.875rem;
            height: 0.875rem;
            background: url('@/assets/image/material/suspend_icon.png') no-repeat;
            background-size: 100%;
            position: absolute;
            top: 1rem;
            left: 4.75rem;
            z-index: 99;
        }

        .radar_icon {
            position: absolute;
            top: 0.625rem;
            right: 0.75rem;
            width: 1.375rem;
            height: 1.375rem;
            background: url('@/assets/image/material/radar_red.png') no-repeat;
            background-size: 100%;
            z-index: 1;
        }

        .audio {
            border: 0.0625rem solid #eaeaea;
            box-sizing: border-box;
            border-bottom: none;
            text-align: center;
            padding: 3.125rem 0.625rem 0.625rem;

            audio {
                width: 100%;
                height: 2.5rem;
            }
        }
    }

    .container_text {
        margin-top: -0.25rem;
        padding: 0.625rem;
        border: 0.0625rem solid #eaeaea;
        border-top: none;

        .tagList {
            width: 100%;
            display: flex;
            overflow: hidden;
            height: 1.875rem;
            align-items: center;
            font-size: 0.875rem;
            color: #ff6b00;

            .tag_item {
                padding: 0.25rem;
                background: #fff;
                border: 0.0625rem solid #ffc69e;
                border-radius: 0.125rem;
                margin-right: 0.625rem;
                cursor: pointer;

                &:nth-child(1) {
                    margin-left: 0;
                }

                &:nth-child(n + 5) {
                    display: none;
                }
            }
        }

        .describe {
            // width: 17.875rem;
            height: 0.875rem;
            margin: 0.75rem 0 0.5rem;
            line-height: 0.875rem;
            font-size: 0.875rem;
            display: flex;
            align-items: center;

            .describe_text {
                display: inline-block;

                // width: 15.9375rem;
                white-space: nowrap;
                overflow: hidden;
                text-overflow: ellipsis;
            }
        }

        .time {
            display: flex;
            justify-content: space-between;
            height: 1.125rem;
            line-height: 1.125rem;
            color: #969696;
            font-weight: 300;
            font-size: 0.75rem;
        }

        .tag_box {
            height: 22px;
            overflow: hidden;
        }
    }

    .iconList {
        display: flex;
        align-items: center;
        justify-content: space-around;
        border-radius: 0.125rem;
        border: 0.0625rem solid #eaeaea;
        border-top: none;
        height: 2.5rem;

        .icon_item {
            width: 1.1875rem;
            height: 1.1875rem;
            cursor: pointer;

            img {
                width: 100%;
                height: 100%;
            }
        }
    }
}
</style>
